package com.sky.service.impl;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportServer;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServerImpl implements ReportServer {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WorkspaceService workspaceService;
    @Autowired
    private UserMapper userMapper;
    /**
     * 统计指定时间区间内的营业额数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {

        //当前集合用于存放从begin 到end 范围内的每天的日期
        ArrayList<LocalDate> dataList = new ArrayList<>();
        dataList.add(begin);
        while (!equals(end)){
            begin =begin.plusDays(1);
            dataList.add(begin);
        }

        List<Double> turnoverList =new ArrayList<>();
        for (LocalDate date :dataList) {
            //查询date日期对应的营业额数据，营业额是状态为“已完成”状态的订单
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime =LocalDateTime.of(date,LocalTime.MAX);

            HashMap map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover =orderMapper.sumByMap(map);
            turnover =turnover==null?0.0:turnover;
            turnoverList.add(turnover);
        }
        StringUtils.join(dataList,",");
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dataList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 统计指定时间区间内的用户数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {


        //当前集合用于存放从begin 到end 范围内的每天的日期
        ArrayList<LocalDate> dataList = new ArrayList<>();
        dataList.add(begin);
        while (!equals(end)){
            begin =begin.plusDays(1);
            dataList.add(begin);
        }
        //每天新增数量
        List<Integer> newUSerList = new ArrayList<>();
        //存放每天的用户总量
        List<Integer> totalUserList =new ArrayList<>();
        for (LocalDate date: dataList) {
            //获取当前日期的开始日期
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //获取当前日期的末尾日期
            LocalDateTime endTime =LocalDateTime.of(date,LocalTime.MAX);
            HashMap map = new HashMap();

            map.put("end",endTime);
            //总用户数量
            Integer totalUser = userMapper.countByMap(map);
            totalUser = totalUser==null?0:totalUser;
            totalUserList.add(totalUser);
            map.put("begin",beginTime);
            //新增用户数量
            Integer newUser = userMapper.countByMap(map);
            newUser = newUser==null?0:newUser;
            newUSerList.add(newUser);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dataList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUSerList,","))
                .build();
    }
    /**
     * 统计指定时间区间内的订单数据
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin 到end 范围内的每天的日期
        ArrayList<LocalDate> dataList = new ArrayList<>();
        dataList.add(begin);
        while (!equals(end)){
            begin =begin.plusDays(1);
            dataList.add(begin);
        }
        //存放每天总订单数
        List<Integer> orderCountList = new ArrayList<>();
        //存放每天有效总订单数
        List<Integer> validOrderCountList =new ArrayList<>();

        //遍历dateList集合，查询每天的有效订单数和订单总数
        for (LocalDate date: dataList) {
            //获取当前日期的开始日期
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            //获取当前日期的末尾日期
            LocalDateTime endTime =LocalDateTime.of(date,LocalTime.MAX);
            //查询每天订单总数
            Integer orderCount=getOrderCount(beginTime,endTime,null);
            //查询每天有效订单数
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
        //计算时间区间的订单总数
        Integer totalOrderCount   = orderCountList.stream().reduce(Integer::sum).get();
        //计算时间区间的有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //计算订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount!=0){
            orderCompletionRate= (double) (validOrderCount/totalOrderCount);
        }


        return OrderReportVO.builder()
                .dateList(StringUtils.join(dataList,","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .build();
    }

    /**
     * 根据条件统计订单数量
     * @param begin
     * @param end
     * @param status
     * @return
     */
    private Integer getOrderCount(LocalDateTime begin,LocalDateTime end ,Integer status){
        HashMap map = new HashMap();
        map.put("begin",begin);
        map.put("end",end);
        map.put("status", status);
        return orderMapper.countByMap(map);
    }

    /**
     * 统计指定时间内的top10的销量排名
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {

            //获取当前日期的开始日期
            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            //获取当前日期的末尾日期
            LocalDateTime endTime =LocalDateTime.of(end,LocalTime.MAX);

            List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

            List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
            String nameList = StringUtils.join(names, ",");

            List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

             String numberList = StringUtils.join(numbers, ",");


        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出近30天运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response)   {
        //查询数据库 ，获取营业数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);

        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);
        //通过poi将数据写入到excel文件中
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模版.xlsx");
        //基于模版文件创造一个新的Excel文件
        try {
            XSSFWorkbook excel = new XSSFWorkbook(resourceAsStream);

            //获取表格文件的Sheet1页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据--时间
            XSSFRow row = sheet.getRow(1);
            row.getCell(1).setCellValue("时间："+dateBegin+"至"+dateEnd);

            //填充概览数据
            //获得第四行
            XSSFRow row4 = sheet.getRow(3);
            //设置营业额
            row4.getCell(2).setCellValue(businessData.getTurnover());
            //设置订单完成率
            row4.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //设置新增用户数
            row4.getCell(6).setCellValue(businessData.getNewUsers());
            //获取第五行
            XSSFRow row5 = sheet.getRow(4);
            //设置有效订单数
            row5.getCell(2).setCellValue(businessData.getValidOrderCount());
            //设置平均客单价
            row5.getCell(4).setCellValue(businessData.getUnitPrice());


            //填充明细数据

            for (int i = 0; i < 30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO dataVO = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MIN));
                //获得某一行
                XSSFRow row1 = sheet.getRow(7 + i);
                row1.getCell(1).setCellValue(date.toString());
                row1.getCell(2).setCellValue(dataVO.getTurnover());
                row1.getCell(3).setCellValue(dataVO.getValidOrderCount());
                row1.getCell(4).setCellValue(dataVO.getOrderCompletionRate());
                row1.getCell(5).setCellValue(dataVO.getUnitPrice());
                row1.getCell(6).setCellValue(dataVO.getNewUsers());

            }



            //通过输出流将Excel文件下载到客户端浏览器

            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            //关闭资源
            excel.close();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
